package com.lalilu.homework9.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lalilu.homework9.R;
import com.lalilu.homework9.room.MyRoomDatabase;
import com.lalilu.homework9.room.User;
import com.lalilu.homework9.room.UserDao;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class RoomFragment extends Fragment {

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        UserDao userDao = MyRoomDatabase.getInstance(requireActivity()).userDao();

        EditText _username = view.findViewById(R.id.sqlite_username);
        EditText _age = view.findViewById(R.id.sqlite_age);
        Button _insert = view.findViewById(R.id.sqlite_insert);
        Button _search = view.findViewById(R.id.sqlite_search);
        TextView _output = view.findViewById(R.id.sqlite_output);

        _output.post(() -> {
            _output.setText(getStringFromList(userDao.getAll()));
        });

        _search.setOnClickListener(v -> {
            _output.setText(getStringFromList(userDao.getByAge(18)));
        });

        _insert.setOnClickListener(v -> {
            try {
                User user = new User();
                user.username = _username.getText().toString();
                user.age = Long.parseLong(_age.getText().toString());
                userDao.insert(user);
                Toast.makeText(requireActivity(), "添加成功", Toast.LENGTH_SHORT).show();
            } catch (NumberFormatException e) {
                Toast.makeText(requireActivity(), "输入格式错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getStringFromList(List<User> users) {
        StringBuilder stringBuilder = new StringBuilder();

        for (User user : users) {
            stringBuilder.append("id: ").append(user.id)
                    .append("    username: ").append(user.username)
                    .append("    age: ").append(user.age)
                    .append("\n");
        }

        return stringBuilder.toString();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sqlite, container, false);
    }
}